﻿using AutoMapper;
using B.S.BaseData.Domain;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infratructure.Interfares;
using B.S.BaseData.Read.Api.Application.Command.UserRoleCommand;
using B.S.BaseData.Read.Api.Dtos;
using MediatR;

namespace B.S.BaseData.Read.Api.Application.CommandHander.UserRoleHander
{
    public class GetUserRole2CommandHander : IRequestHandler<GetUserRole2Command, ApiResult<List<GetUserRole2Dto>>>
    {

        private readonly IMapper mapper;
        private readonly IBaseRequsitory<User> userRequsitory;
        private readonly IBaseRequsitory<Role> roleRequsitory;
        private readonly IBaseRequsitory<UserRole> userroleRequsitory;

        public GetUserRole2CommandHander(IMapper mapper, IBaseRequsitory<User> userRequsitory, IBaseRequsitory<Role> roleRequsitory, IBaseRequsitory<UserRole> userroleRequsitory)
        {
            this.mapper = mapper;
            this.userRequsitory = userRequsitory;
            this.roleRequsitory = roleRequsitory;
            this.userroleRequsitory = userroleRequsitory;
        }
        /// <summary>
        /// 属于**角色的显示
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<List<GetUserRole2Dto>>> Handle(GetUserRole2Command request, CancellationToken cancellationToken)
        {
            ApiResult<List<GetUserRole2Dto>> result = new ApiResult<List<GetUserRole2Dto>>();

            var linq = from u in userRequsitory.GetAllAsync()
                       join ur in userroleRequsitory.GetAllAsync() on u.UserId equals ur.UserId
                       join role in roleRequsitory.GetAllAsync() on ur.RoleId equals role.RoleId
                       where request.RoleId== ur.RoleId
                       select new GetUserRole2Dto
                       {
                           UserRoleId = ur.UserRoleId,
                           UserId = u.UserId,
                           UserName = u.UserName,
                           RoleId = role.RoleId,
                           RoleName = role.RoleName
                       };

            result.Code = ApiEnum.显示成功;
            result.Msg = ApiEnum.显示成功.ToString();
            var entity = linq.OrderBy(x => x.UserId).ToList();

            result.Data = mapper.Map<List<GetUserRole2Dto>>(entity);

            return Task.FromResult(result);

        }
    }
}
